package gat.common.util;



import com.aliyun.agency20221216.Client;
import com.aliyun.agency20221216.models.*;
import com.aliyun.teautil.models.RuntimeOptions;
import com.bitsun.core.common.exception.AppException;
import gat.RedisService;
import gat.common.config.AliConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

@Slf4j
@Component
public class AliUtil {

    @Autowired
    private AliConfig aliConfig;

    @Autowired
    private RedisService redisService;


    public String getPrimaryUId(String accountId) throws Exception {
        // 根据accountId 从缓存中查询 查询不到 再根据接口轮询 查询到之后 设置缓存
        String primaryUId = redisService.get("primary:ali:" + accountId);
        if (StringUtils.isNotBlank(primaryUId)) {
            return primaryUId;
        }

        for (AliConfig.AliAccount account : aliConfig.getAccounts()) {
            try {
                getAccountInfo(account.getAccountId(), accountId);
                primaryUId = account.getAccountId();
            } catch (Exception ex) {
                log.error("该账号的主账号不是："+account.getAccountId());
            }
        }
        if (StringUtils.isBlank(primaryUId)) {
            throw new AppException("该账号的主账号未查询到，请联系销售人员");
        }
        redisService.set("primary:ali:" + accountId, primaryUId);
        return primaryUId;

    }

    public GetAccountInfoResponseBody.GetAccountInfoResponseBodyAccountInfoListAccountInfo getAccountInfo(String accountId) throws Exception {
        String primaryUId = getPrimaryUId(accountId);
        Client client = aliConfig.createClient(primaryUId);
        GetAccountInfoRequest getAccountInfoRequest = new GetAccountInfoRequest()
                .setUid(Long.parseLong(accountId))
                .setCurrentPage(1)
                .setPageSize(1)
                ;
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            GetAccountInfoResponse accountInfoWithOptions = client.getAccountInfoWithOptions(getAccountInfoRequest, runtime);
            if (accountInfoWithOptions.getStatusCode() != 200 && !StringUtils.equals(accountInfoWithOptions.getBody().getCode(), "200")) {
                throw new AppException("账号查询异常，请输入正确的账号id或者联系销售人员查看");
            }
            GetAccountInfoResponseBody.GetAccountInfoResponseBodyAccountInfoListAccountInfo getAccountInfoResponseBodyAccountInfoListAccountInfo = accountInfoWithOptions.body.accountInfoList.accountInfo.get(0);
            return getAccountInfoResponseBodyAccountInfoListAccountInfo;
        } catch (Exception _error) {
            throw new AppException("账号查询异常，请输入正确的账号id或者联系销售人员查看");
        }
    }

    public GetAccountInfoResponseBody.GetAccountInfoResponseBodyAccountInfoListAccountInfo getAccountInfo(String primaryUId, String accountId) throws Exception {
        Client client = aliConfig.createClient(primaryUId);
        GetAccountInfoRequest getAccountInfoRequest = new GetAccountInfoRequest()
                .setUid(Long.parseLong(accountId))
                .setCurrentPage(1)
                .setPageSize(1)
                ;
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            GetAccountInfoResponse accountInfoWithOptions = client.getAccountInfoWithOptions(getAccountInfoRequest, runtime);
            if (accountInfoWithOptions.getStatusCode() != 200 && !StringUtils.equals(accountInfoWithOptions.getBody().getCode(), "200")) {
                throw new AppException("账号查询异常，请输入正确的账号id或者联系销售人员查看");
            }
            GetAccountInfoResponseBody.GetAccountInfoResponseBodyAccountInfoListAccountInfo getAccountInfoResponseBodyAccountInfoListAccountInfo = accountInfoWithOptions.body.accountInfoList.accountInfo.get(0);
            return getAccountInfoResponseBodyAccountInfoListAccountInfo;
        } catch (Exception _error) {
            throw new AppException("账号查询异常，请输入正确的账号id或者联系销售人员查看");
        }
    }

    public GetCreditInfoResponseBody.GetCreditInfoResponseBodyData getAccountBalance(String accountId) throws Exception {
        String primaryUId = getPrimaryUId(accountId);
        Client client = aliConfig.createClient(primaryUId);
        GetCreditInfoRequest getCreditInfoRequest = new GetCreditInfoRequest()
                .setUid(Long.parseLong(accountId))
                ;
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            GetCreditInfoResponse creditInfoWithOptions = client.getCreditInfoWithOptions(getCreditInfoRequest, runtime);
            if (creditInfoWithOptions.getStatusCode() != 200&& !StringUtils.equals(creditInfoWithOptions.getBody().getCode(), "200")) {
                throw new AppException("账号查询异常，请输入正确的账号id或者联系销售人员查看");
            }
            return creditInfoWithOptions.getBody().data;
        } catch (Exception _error) {
            throw new AppException("账号查询异常，请输入正确的账号id或者联系销售人员查看");
        }
    }

    // 阿里云需要查询出来原先的 再累加上充值金额
    public void transferCredit(String accountId, Long amount) throws Exception {
        String primaryUId = getPrimaryUId(accountId);
        Client client = aliConfig.createClient(primaryUId);
        BigDecimal bigDecimalValue = new BigDecimal(amount);
        BigDecimal dividedValue = bigDecimalValue.divide(new BigDecimal("1000000"), 6, RoundingMode.HALF_UP);
        String result = dividedValue.toPlainString();

        SetCreditLineRequest setCreditLineRequest = new SetCreditLineRequest()
                .setUid(Long.parseLong(accountId))
                .setCreditLine(result);
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            SetCreditLineResponse setCreditLineResponse = client.setCreditLineWithOptions(setCreditLineRequest, runtime);
            if (setCreditLineResponse.getStatusCode() != 200 && !StringUtils.equals(setCreditLineResponse.getBody().getCode(), "200")) {
                throw new AppException("划拨异常，请联系销售人员");
            }
        }  catch (Exception _error) {
            throw new AppException("划拨异常，请联系销售人员");
        }
    }


    public void editEndUserStatus(String accountId, Integer type) throws Exception {
        String primaryUId = getPrimaryUId(accountId);
        Client client = aliConfig.createClient(primaryUId);

        EditEndUserStatusRequest editEndUserStatusRequest = new EditEndUserStatusRequest()
                .setUid(Long.parseLong(accountId))
                .setCreditStatus(type == 0 ? "postPayThaw" : "postPayFreeze");
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            EditEndUserStatusResponse response = client.editEndUserStatusWithOptions(editEndUserStatusRequest, runtime);
            if (response.getStatusCode() != 200 &&  !StringUtils.equals(response.getBody().getCode(), "200")) {
                throw new AppException("修改客户状态异常，请联系销售人员");
            }
        }  catch (Exception _error) {
            throw new AppException("修改客户状态异常，请联系销售人员");
        }
    }


    public List<GetAccountInfoResponseBody.GetAccountInfoResponseBodyAccountInfoListAccountInfo>  getAccountInfo(String primaryUId, Integer currentPage, Integer pageSize) throws Exception {

        Client client = aliConfig.createClient(primaryUId);
        GetAccountInfoRequest getAccountInfoRequest = new GetAccountInfoRequest()
                .setCurrentPage(currentPage)
                .setPageSize(pageSize)
                .setUserType("1")
                ;
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            GetAccountInfoResponse accountInfoWithOptions = client.getAccountInfoWithOptions(getAccountInfoRequest, runtime);
            if (accountInfoWithOptions.getStatusCode() != 200 && !StringUtils.equals(accountInfoWithOptions.getBody().getCode(), "200")) {
                throw new AppException("账号查询异常，请输入正确的账号id或者联系销售人员查看");
            }
            List<GetAccountInfoResponseBody.GetAccountInfoResponseBodyAccountInfoListAccountInfo> accountInfoList = accountInfoWithOptions.body.accountInfoList.accountInfo;
            return accountInfoList;
        } catch (Exception _error) {
            throw new AppException("账号查询异常，请输入正确的账号id或者联系销售人员查看");
        }
    }

}
